package com.yneusoft.pctask.aop;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yneusoft.common.model.ResponseWrapper;
import com.yneusoft.dao.entity.Department;
import com.yneusoft.dao.entity.DepartmentState;
import com.yneusoft.dao.mapper.DepartmentMapper;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * @Description： 部门管理切面
 * @Author: wbf
 * @Date: 2021/11/25 20:36
 */
@Aspect
@Component
public class DepartmentAop {
    @Autowired
    DepartmentMapper departmentMapper;

    @Before(value = "execution(* com.yneusoft.dao.mapper.DepartmentMapper.insert(..))")
    public void insertDepartment(JoinPoint joinPoint){
        Object[] args = joinPoint.getArgs();
        Department department =  (Department) args[0];
        String stateName = DepartmentState.dataMap.get(department.getStateId()).getName();
        department.setStateName(stateName);
        /**
         * 获取当前时间
         */
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyyMMdd");
        String currentTime = df.format(now);
        /**
         * 确定等级
         */
        Integer level = 0; //默认等级
        LambdaQueryWrapper<Department> getLevel = new LambdaQueryWrapper<>();
        getLevel.eq(Department::getAid,department.getFatherAid());
        Department farther = departmentMapper.selectOne(getLevel);
        if(farther != null){ level = farther.getLevel()+1;}
        department.setLevel(level);
        /**
         * 确定第几个
         */
        Integer count = 0;
        LambdaQueryWrapper<Department> getCount = new LambdaQueryWrapper<>();
        String before = now.toString().split("T")[0]+" 00:00:00";
        String after = now.toString().split("T")[0]+" 23:59:59";
        getCount.between(Department::getCreateTime,before,after);
        count = departmentMapper.selectCount(getCount);
        String code = currentTime+String.format("%02d",level)+String.format("%04d",count);
        department.setCode(code);
    }
}
